<template>
  <view class="membersList flex flex-column align-center">
    <s-header-title ref="headerTitle" isDisplayBack title="家庭成员" is-fixed background="#FFFFFF"
                    @getPageHeight="getPageHeight">
      <template>
        <view class="membersList_headerTitle">
          <text class="membersList_headerTitle_text">{{ selectedFamilyDetail.name || '暂无家庭名称' }}</text>
        </view>
      </template>
    </s-header-title>
    <view :style="{height:`${headerHeight}px`}"></view>
    <view class="membersList_tip_top hW_80 flex align-center justify-center">
      <text class="membersList_tip_top_text">可长按右侧图标上下拖动排序</text>
    </view>
    <scroll-view scroll-y>
      <l-drag :list="membersList"
              :column="1"
              gridHeight="135rpx"
              longpress
              @change="change"
      >
        <template #grid="{active, index, content}">
          <view class="flex flex-column align-center" @touchstart="selectInfo(content)">
            <view class="flex align-center justify-between wh_702 bg_FFFFFF mb_15"
                  style="padding: 15rpx;"
                  @click="goToPath(content)"
            >
              <view class="flex">
                <image-avater :src="`${content.avatar}`" :width="92" :height="92"></image-avater>
                <view class="module_left ml_20 flex flex-column justify-around">
                  <view class="top flex align-center">
                    <view class="name">
                      {{ !!content.username ? content.username : content.remark }}
                    </view>
                    <view class="remark flex align-center justify-center ml_15"
                          v-if="content.username != '' && !!content.remark">
                      {{ content.remark }}
                    </view>
                  </view>
                  <view class="bottom flex align-center">
                    <image v-if="content.gender == 1"
                           :src="`${IMG_URL}/index/user_men.png`"
                           style="width: 21rpx;height: 23rpx;"></image>
                    <image v-else
                           :src="`${IMG_URL}/index/user_women.png`"
                           style="width: 21rpx;height: 23rpx;"></image>
                    <view class="ml_9" v-if="!!content.full_year">
                      {{ !!content.full_year ? `${content.full_year}` : '' }}
                    </view>
                    <view class="ml_22" v-if="!!content.shuxing.animal">
                      {{ !!content.shuxing.animal ? `${content.shuxing.animal}` : '' }}
                    </view>
                    <view class="ml_22" v-if="!!content.shuxing.constellation">
                      {{ !!content.shuxing.constellation ? `${content.shuxing.constellation}座` : '' }}
                    </view>
                    <view class="ml_22" style="color: #FF4206;" @click.stop="peopleDataPath(content)">
                      编辑资料
                    </view>
                  </view>
                </view>
              </view>
              <image class="wh_28 hW_28"
                     :src="`${IMG_URL}/index/family_sort.png`"
              ></image>
            </view>
          </view>
        </template>
      </l-drag>
    </scroll-view>
    <view class="hW_150"></view>

    <!--    <bottom-button title="添加家庭成员" class="fixed mt-25" isFixed-->
    <!--                   @elementClick="addFamilyMembers"></bottom-button>-->
    <!--    <view style="height: 150rpx;"></view>-->

    <!-- 家庭成员弹窗 -->
    <first_popup ref="familyMemberPopUp" @closePopup="surnameClose">
      <template #content>
        <view class="familyMemberPopUp flex flex-column align-center">
          <view class="familyMemberPopUp_title mt_45">
            <view class="familyMemberPopUp_title_name">
              添加家庭成员
            </view>
            <view class="familyMemberPopUp_title_detail">
              {{ selectedFamilyDetail.familyName }}
            </view>
          </view>
          <image class="familyMemberPopUp_icon z_1" :src="`${IMG_URL}/index/add_icon.png`"></image>
          <scroll-view :scroll-left="familyMembersProfileListScroll.scrollLeft" :scroll-x="true"
                       class="familyMemberPopUp_scrollView mt_32"
                       scroll-with-animation>
            <view :id="selectProfileIndex == index ? 'familyMemberPopUp_scrollView_list':''"
                  class="familyMemberPopUp_scrollView_list" v-for="(item,index) in familyMembersProfileList" :style="{
              padding:index == 0 ? '0 12rpx 0 0':index == familyMembersProfileList.length?'0 0 0 12rpx':'0 12rpx'
            }" :key="index" @click="changeTab(index)">
              <image-avater id="imageAvater" :width="selectProfileIndex == index?111 : 78"
                            :height="selectProfileIndex == index? 111 : 78" :src="item.img"
                            :is-order="selectProfileIndex == index"
                            :border-width="4" border-color="#FF4206"></image-avater>
            </view>
          </scroll-view>
          <view class="familyMemberPopUp_editInfo flex align-center justify-between mt_64">
            <view class="familyMemberPopUp_editInfo_left flex align-center justify-center">
              <input type="text" v-model="familyPopupFrom.nameBox" placeholder="尊姓" :focus="suernameFocus"
                     placeholder-class="familyMemberPopUp_editInfo_placeholder" @input="suernameInput"
                     @blur="surnameBlur">
            </view>
            <view class="familyMemberPopUp_editInfo_right  flex align-center justify-center">
              <input type="text" v-model="familyPopupFrom.appellation" placeholder="大名"
                     placeholder-class="familyMemberPopUp_editInfo_placeholder" @input="nameInput" @blur="nameBlur">
            </view>
          </view>
        </view>
      </template>
    </first_popup>

  </view>
</template>

<script>
  import HeaderTitle from '@/pages/familyPage/components/headerTitle.vue';
  import First_popup from '@/pages/familyPage/components/first_popup.vue';
  import ImageAvater from '@/sheep/components/s-avatar/s-avatar.vue';
  import sheep from '@/sheep';
  import LDrag from '@/uni_modules/lime-drag/components/l-drag/l-drag.vue';

  export default {
    components: { LDrag, ImageAvater, First_popup, HeaderTitle },
    props: {
      options: {
        type: Object,
        default: () => {
          return {};
        },
      },
    },
    data() {
      return {
        // 头部高度
        headerHeight: 0,
        // 家庭成员列表
        membersList: [],
        // 家庭成员头像列表
        familyMembersProfileList: [],
        // 选中的家庭成员头像的下标
        selectProfileIndex: 2,
        familyPopupFrom: {
          nameBox: '',
          appellation: '',
        },
        // 获取家庭成员参数
        getFamilyMemberListParams: {
          family_id: '',
          page: 0,
        },
        // 浮窗按钮的配置
        bottomFlag: false,
        systemInfo: {},
        height_list: uni.upx2px(126),
        familyMembersProfileListScroll: {
          scrollLeft: 0,
          allWidth: 0,
          width: 0,
          selectWidth: 0,
        },
        suernameFocus: false,
        shadowInfo: {},
        selectedFamilyDetail: {},
        selectMemberInfo: {},
      };
    },
    computed: {
      IMG_URL() {
        return sheep.$store('AI').sq_image_path;
      },
      nc_image() {
        return sheep.$store('AI').nc_image;
      },
      listHeight() {
        return Number(this.systemInfo.windowHeight - this.headerHeight);
        // - uni.upx2px(230)
      },
    },
    watch: {
      familyMembersProfileListScroll: {
        deep: true,
        handler(newValue, oldValue) {
          this.familyMembersProfileListScroll.scrollLeft = newValue.allWidth - newValue.width / 2 + newValue.selectWidth / 2;
        },
      },
    },
    mounted() {
      // 获取家庭详情
      this.getFamilyDetail();
      this.systemInfo = uni.getSystemInfoSync();
      this.setFamilyMemberList();
      uni.$on('getFamilyMemberList', () => {
        this.membersList = [];
        this.getFamilyMemberListParams.page = 1;
        this.setFamilyMemberList();
      });
    },
    onReady() {
      this.$nextTick(() => {
        this.getBottomButton();
      });
    },
    methods: {
      getPx(number) {
        return uni.upx2px(number);
      },
      async getFamilyDetail() {
        const { data } = await sheep.$api.family.getFamilyCulture({
          family_id: this.options.family_id,
        });
        this.selectedFamilyDetail = data;
      },
      suernameInput(e) {
        if (e.target.value.length > 1) {
          let arr;
          arr = e.target.value.match(/[\u4e00-\u9fa5]/g);
          if (!!arr) {
            this.$set(this.familyPopupFrom, 'nameBox', arr.join('').substring(0, 2));
          } else {
            this.$set(this.familyPopupFrom, 'nameBox', '');
          }
        }
      },
      surnameBlur(e) {
        if (e.target.value.length > 0) {
          let arr;
          arr = e.target.value.match(/[\u4e00-\u9fa5]/g);
          if (!!arr) {
            this.$set(this.familyPopupFrom, 'nameBox', arr.join('').substring(0, 2));
          } else {
            this.$set(this.familyPopupFrom, 'nameBox', '');
          }
        }
      },
      nameInput(e) {
        if (e.target.value.length > 1) {
          let arr;
          arr = e.target.value.match(/[\u4e00-\u9fa5]/g);
          if (!!arr) {
            this.$set(this.familyPopupFrom, 'appellation', arr.join('').substring(0, 4));
          } else {
            this.$set(this.familyPopupFrom, 'appellation', '');
          }
        }
      },
      nameBlur(e) {
        if (e.target.value.length > 0) {
          let arr;
          arr = e.target.value.match(/[\u4e00-\u9fa5]/g);
          if (!!arr) {
            this.$set(this.familyPopupFrom, 'appellation', arr.join('').substring(0, 4));
          } else {
            this.$set(this.familyPopupFrom, 'appellation', '');
          }
        }
      },
      getBottomButton() {
        // const query = uni.createSelectorQuery().in(this)
        // query.select('.membersList_all').boundingClientRect(data => {
        //   const rpx = this.systemInfo.windowWidth / 750
        //   this.bottomFlag = (this.headerHeight + data.top + data.height) > this.systemInfo.windowHeight - (200 * rpx)
        // }).exec()
      },
      getPageHeight(number) {
        this.headerHeight = number;
      },
      // 跳转用户详情
      goToPath(item) {
        sheep.$router.go('/pages/familyPage/memberDetails', {
          id: item.id,
          family_id: this.options.family_id,
        });
      },
      peopleDataPath(row) {
        // this.$nav.navigateTo('/pages/familyPage/personalData', {
        //   member_id: row.id,
        //   name: row.username,
        // });
        sheep.$router.go('/pages/familyPage/personalData', {
          member_id: row.id,
          name: row.username,
          family_id: this.options.family_id,
        });
      },
      // 添加家庭成员
      async addFamilyMembers() {
        let { data, status, msg } = await getConfigFamilyImage();
        if (status != '200') {
          uni.showToast({
            title: msg,
            icon: 'none',
          });
          return;
        }
        this.familyMembersProfileList = data.list;
        setTimeout(() => {
          this.suernameFocus = true;
        }, 100);
        this.$refs.familyMemberPopUp.openPopup({
          title: '添加家庭成员',
          showTitle: false,
          maskClick: false,
          popupBackground: true,
          confirm: () => {
            if (this.familyPopupFrom.nameBox == '') {
              uni.showToast({
                title: '姓氏尚未填写',
                icon: 'none',
              });
              return;
            }
            if (this.familyPopupFrom.appellation == '') {
              uni.showToast({
                title: '名称尚未填写',
                icon: 'none',
              });
              return;
            }
            addFamilyMember({
              family_id: this.$store.state.shiqinStore.selectedId,
              surname: this.familyPopupFrom.nameBox,
              daimyo: this.familyPopupFrom.appellation,
              img: this.familyMembersProfileList[this.selectProfileIndex].img,
              sex: this.familyMembersProfileList[this.selectProfileIndex].sex,
            }).then(res => {
              this.suernameFocus = false;
              if (res.status == '200') {
                uni.showToast({
                  title: '添加成功',
                  icon: 'none',
                });
              } else {
                uni.showToast({
                  title: res.msg,
                  icon: 'none',
                });
              }
              this.$refs.familyMemberPopUp.closePopup();
              this.familyPopupFrom.appellation = '';
              this.familyPopupFrom.nameBox = '';
              this.membersList = [];
              this.setFamilyMemberList();
            });
          },
        });
      },
      surnameClose() {
        this.suernameFocus = false;
      },
      // 获取家庭成员
      async setFamilyMemberList() {
        this.getFamilyMemberListParams.family_id = this.options.family_id;
        let { data } = await sheep.$api.family.getFamilyMemberList(this.getFamilyMemberListParams);
        this.membersList = data;
        // data.list.data.forEach(item => {
        //   this.membersList.push(item)
        // })
        // this.getFamilyMemberListParams.total = data.list.total
        // this.$nextTick(() => {
        //   this.$refs.headerTitle.getPageHeight()
        //   this.getBottomButton()
        //   this.$forceUpdate()
        // })
      },
      scrolltolower() {
        if (this.getFamilyMemberListParams.page * this.getFamilyMemberListParams.pagesize < this.getFamilyMemberListParams.total) {
          this.getFamilyMemberListParams.page++;
          this.setFamilyMemberList();
        }
      },
      changeTab(index) {
        this.selectProfileIndex = index;
        setTimeout(() => {
          this.moveTo(index);
        }, 10);
      },
      moveTo(index) {
        const query = uni.createSelectorQuery().in(this);
        query.select('.familyMemberPopUp_scrollView').boundingClientRect(data => {
          this.familyMembersProfileListScroll.width = data.width;
        }).exec();
        query.select('#familyMemberPopUp_scrollView_list').boundingClientRect(rect => {
          this.familyMembersProfileListScroll.selectWidth = rect.width;
        }).exec();
        query.selectAll('.familyMemberPopUp_scrollView_list').boundingClientRect(rect => {
          if (rect.length > 0) {
            this.familyMembersProfileListScroll.allWidth = 0;
            rect.forEach((item, i) => {
              if (i < index) {
                this.familyMembersProfileListScroll.allWidth += Number(item.width);
              }
            });
          }
        }).exec();
      },
      async changeList(list) {
        console.log('数组改变后的=>', list);
        let length = list.list.length;
        let arr1 = [...list.list];
        let arr = [];
        // arr1.sort((a, b) => {
        //   return a.SortNumber - b.SortNumber
        // })
        arr1.forEach(item => {
          arr.push({
            id: item.id,
            weight: length,
          });
          length--;
        });
        await updateMemberSort({
          member_sort: arr,
        });
      },
      async change(e) {
        const { code, msg } = await sheep.$api.family.checkAuth({
          family_id: this.options.family_id,
          action: 'add',
        });
        if (code != 1) {
          sheep.$helper.toast(msg);
          await this.setFamilyMemberList()
          return;
        }
        let arr = [];
        e.forEach(item => {
          arr.push(item.content.id);
        });
        sheep.$api.family.updateFamilyMemberSort({
          family_id: this.options.family_id,
          member_id: this.selectMemberInfo.id,
          ids: arr.join(','),
        });
      },
      selectInfo(info) {
        this.selectMemberInfo = info;
      },
    },
  };
</script>

<style lang="scss">
  .module_left {
    .top {
      font-family: PingFang SC, PingFang SC;
      font-weight: 500;
      font-size: 30rpx;
      color: #4B4B4B;

      .remark {
        width: 66rpx;
        height: 30rpx;
        background: #FF7950;
        border-radius: 15rpx 15rpx 15rpx 15rpx;
        font-family: PingFang SC, PingFang SC;
        font-weight: 500;
        font-size: 16rpx;
        color: #FFFFFF;
      }
    }

    .bottom {
      font-family: PingFang SC, PingFang SC;
      font-weight: 500;
      font-size: 24rpx;
      color: #696969;
    }
  }

  .membersList {
    width: 750rpx;
    min-height: 100vh;
    overflow: hidden;

    .membersList_headerTitle {
      position: absolute;
      bottom: -26rpx;
      left: 50%;
      transform: translateX(-50%);

      .membersList_headerTitle_text {
        font-family: PingFang SC, PingFang SC;
        font-weight: 500;
        font-size: 20rpx;
        color: #A0A0A0;
      }
    }

    .membersList_all {
      width: 702rpx;
      background: #F5F5F5;
      border-radius: 20rpx 20rpx 20rpx 20rpx;
      padding: 20rpx 0;
      overflow: hidden;

      .membersList_all_search {
        width: 656rpx;
        height: 80rpx;
        background: #E5E5E5;
        border-radius: 20rpx 20rpx 20rpx 20rpx;

        .membersList_all_search_image {
          width: 25rpx;
          height: 25rpx;
        }

        .membersList_all_search_text {
          font-family: PingFang SC, PingFang SC;
          font-weight: 500;
          font-size: 26rpx;
          color: #4B4B4B;
        }
      }

      .membersList_all_list {
        width: 656rpx;
        display: grid;
        grid-template-columns: repeat(5, 92rpx);
        grid-row-gap: 16rpx;

        .membersList_all_list_every {
          position: relative;

          .membersList_all_list_every_label {
            width: 84rpx;
            height: 27rpx;
            background: #FFFFFF;
            border-radius: 14rpx 14rpx 14rpx 14rpx;
            //border: 1rpx solid #9B9B9B;
            position: absolute;
            top: 77rpx;
            left: 50%;
            transform: translateX(-50%);

            .membersList_all_list_every_label_text {
              font-family: PingFang SC, PingFang SC;
              font-weight: 500;
              font-size: 18rpx;
              color: #FFFFFF;
            }
          }

          .membersList_all_list_every_name {
            .membersList_all_list_every_name_text {
              font-family: PingFang SC, PingFang SC;
              font-weight: 500;
              font-size: 24rpx;
              color: #292929;
            }
          }

          .membersList_all_list_every_text {
            white-space: nowrap;
            font-family: PingFang SC, PingFang SC;
            font-weight: 400;
            font-size: 24rpx;
            color: #292929;
          }
        }
      }
    }

    .membersList_tip {


      .membersList_tip_bottom {
        width: 336rpx;
        height: 80rpx;
        background: #FF4206;
        border-radius: 57rpx 57rpx 57rpx 57rpx;
        position: fixed;
        bottom: 50rpx;
        left: 50%;
        transform: translateX(-50%);
        z-index: 10;

        .membersList_tip_bottom_text {
          font-family: PingFang SC, PingFang SC;
          font-weight: 500;
          font-size: 30rpx;
          color: #FFFFFF;
        }
      }
    }

    .familyMemberPopUp {
      width: 506rpx;

      .familyMemberPopUp_title {
        width: 454rpx;

        .familyMemberPopUp_title_name {
          font-family: PingFang SC, PingFang SC;
          font-weight: 500;
          font-size: 48rpx;
          color: #292929;

        }

        .familyMemberPopUp_title_detail {
          font-family: PingFang SC, PingFang SC;
          font-weight: 500;
          font-size: 24rpx;
          color: #9F9F9F;
        }
      }

      .familyMemberPopUp_icon {
        width: 147rpx;
        height: 147rpx;
        position: absolute;
        top: 0;
        right: 0;
      }

      .familyMemberPopUp_scrollView {
        width: 506rpx;
        overflow: hidden;
        white-space: nowrap;

        .familyMemberPopUp_scrollView_list {
          display: inline-block;
        }
      }

      .familyMemberPopUp_editInfo {
        width: 506rpx;

        .familyMemberPopUp_editInfo_left {
          width: 239rpx;
          height: 80rpx;
          background: #FFFFFF;
          border-radius: 40rpx 40rpx 40rpx 40rpx;
          border: 2rpx solid #707070;

          input {
            text-align: center;
          }
        }

        .familyMemberPopUp_editInfo_right {
          width: 239rpx;
          height: 80rpx;
          background: #FFFFFF;
          border-radius: 40rpx 40rpx 40rpx 40rpx;
          border: 2rpx solid #707070;

          input {
            text-align: center;
          }
        }

        .familyMemberPopUp_editInfo_placeholder {
          font-family: PingFang SC, PingFang SC;
          font-weight: 500;
          font-size: 28rpx;
          color: #A0A0A0;
        }
      }
    }
  }


  .membersList_tip_top {
    .membersList_tip_top_text {
      font-family: PingFang SC, PingFang SC;
      font-weight: 500;
      font-size: 24rpx;
      color: #A0A0A0;
    }
  }
</style>
